import React, { useEffect, useState } from 'react';
import Web3 from 'web3';
import { useParams } from 'react-router-dom';
import { Rate, Upload, Button, message } from 'antd';

import MarketplaceABI from '../contract/ABIs/Marketplace.json'; // 用户列表合约 ABI
import MaterialListAddr from '../contract/ADDRESSes/MaterialListAddr';
import PurchaseProduct from './PurchaseProduct'; // 引入购买组件
import './ProductDetail.css'; // 引入CSS文件

const ProductDetail = () => {
    const { userAddr, productid } = useParams();
    const [product, setProduct] = useState(null);
    const [reviews, setReviews] = useState([]);

    const web3 = new Web3(window.ethereum);
    const marketplaceContract = new web3.eth.Contract(MarketplaceABI, MaterialListAddr);

    useEffect(() => {
        const fetchProduct = async () => {
            const product = await marketplaceContract.methods.products(productid).call();
            setProduct(product);
            console.log('product', product);
        };
        fetchProduct();
    }, [productid]);

    useEffect(() => {
        const fetchReviews = async () => {
            const reviews = await marketplaceContract.methods.getRecordReviewInfo(productid).call();
            setReviews(reviews);
            console.log('reviews', reviews);
        };
        fetchReviews();
    }, [productid]);

    const handleFavoriteProduct = async () => {
        try {
            const accounts = await web3.eth.getAccounts();
            console.log("productid", productid);
            const result = await marketplaceContract.methods.favoriteProduct(productid).send({ from: accounts[0] });
            console.log('Transaction result:', result);
            alert('商品收藏成功');
        } catch (error) {
            console.error('商品收藏失败', error);
            alert('商品收藏失败');
        }
    };

    if (!product) return <div>加载中...</div>;

    return (
        <div className="product-detail-container">
            <div className="product-image1">
                <img src={`https://ipfs.infura.io/ipfs/${product.ipfsHash}`} alt={product.name} />
            </div>
            <div className="product-info">
                <h2>{product.name}</h2>
                <p>{product.description}</p>
                <p>价格: {Number(product.price)} RMB</p>
                <p>数量: {Number(product.quantity)}</p>
                <p>商品类型: {product.category}</p>
                <p>描述: {product.description}</p>
                <p>商品上架时间: {new Date(Number(product.timestamp) * 1000).toLocaleString()}</p>
                <PurchaseProduct
                    productId={productid}
                    web3={web3}
                    marketplaceContract={marketplaceContract}
                    ipfsHash={product.ipfsHash}
                />
                <button className="favorite-button" onClick={handleFavoriteProduct}>收藏</button>
            </div>

            <div className="reviews-section">
                <h3>商品评价</h3>
                {reviews.length > 0 ? (
                    reviews.map((review, index) => (
                        <div key={index} className="review">
                            <p><strong>评分:</strong>  <Rate
                                value={Number(review.rating)}
                                style={{ fontSize: '24px' }}
                                disabled
                            /> </p>
                            <p><strong>评论:</strong> {review.comment}</p>
                            {review.ipfsHash && (
                                <div className="review-image">
                                    <img src={`https://ipfs.infura.io/ipfs/${review.ipfsHash}`} alt="Review" />
                                </div>
                            )}
                            <p><strong>时间:</strong> {new Date(Number(review.timestamp) * 1000).toLocaleString()}</p>
                        </div>
                    ))
                ) : (
                    <p>暂无评价</p>
                )}
            </div>
        </div>
    );
};

export default ProductDetail;
